<template>
  <div class="app-container calendar-list-container">
    <div class="filter-container">
      <el-button class="filter-item" style="margin-left: 10px;" @click="handleCreate" type="primary" icon="el-icon-edit">{{$t('table.add')}}</el-button>
    </div>

    <el-table :key='tableKey' :data="list" v-loading="listLoading" element-loading-text="给我一点时间" border fit highlight-current-row
      style="width: 100%">
        <el-table-column type="expand">
        <template slot-scope="props">
          <el-form label-position="left" inline class="demo-table-expand">
            <el-form-item :label="$t('table.name')">
              <span>{{ props.row.name }}</span>
            </el-form-item>
            <el-form-item  :label="$t('table.degree')">
              <span>{{ props.row.degree | contactPeopleDegreeFilter}}</span>
            </el-form-item>
            <el-form-item  :label="$t('table.mobile_phone')">
              <span>{{ props.row.mobile_phone }}</span>
            </el-form-item>
            <el-form-item  :label="$t('table.position')">
              <span>{{ props.row.position }}</span>
            </el-form-item>
            <el-form-item  :label="$t('table.gender')">
              <span>{{ props.row.gender | genderFilter }}</span>
            </el-form-item>
            <el-form-item  :label="$t('table.email')" >
              <span>{{ props.row.email }}</span>
            </el-form-item>
            <el-form-item :label="$t('table.telephone')">
              <span>{{ props.row.telephone }}</span>
            </el-form-item>
            <el-form-item :label="$t('table.qq')">
              <span>{{ props.row.qq }}</span>
            </el-form-item>
            <el-form-item :label="$t('table.birthday_date')">
              <span>{{ props.row.birthday_date | timeFilter('{y}-{m}-{d}') }}</span>
            </el-form-item>
            <el-form-item :label="$t('table.native_place')">
              <span>{{ props.row.native_place }}</span>
            </el-form-item>
            <el-form-item :label="$t('table.account')">
              <span>{{ props.row.account }}</span>
            </el-form-item>
            <el-form-item :label="$t('table.password')">
              <span>{{ props.row.password }}</span>
            </el-form-item>
             <el-form-item :label="$t('table.comment')">
              <span>{{ props.row.comment }}</span>
            </el-form-item>
            <el-form-item :label="$t('table.creator')">
              <span>{{ props.row.create_name }}</span>
            </el-form-item>
            <el-form-item :label="$t('table.create_date')">
              <span>{{ props.row.create_date | timeFilter('{y}-{m}-{d} {h}:{i}:{s}') }}</span>
            </el-form-item>
          </el-form>
        </template>
      </el-table-column>

      <el-table-column :label="$t('table.name')"  width="100px" >
        <template slot-scope="scope">
          {{scope.row.name }}
        </template>
      </el-table-column>
      <el-table-column :label="$t('table.degree')"  width="100px"  >
        <template slot-scope="scope">
          <el-tag>{{scope.row.degree | contactPeopleDegreeFilter }}</el-tag>
        </template>
      </el-table-column>
      <el-table-column :label="$t('table.mobile_phone')"  width="120px" >
        <template slot-scope="scope">
          {{scope.row.mobile_phone }}
        </template>
      </el-table-column>
      <el-table-column :label="$t('table.position')"  width="100px" >
        <template slot-scope="scope">
        {{scope.row.position }}
        </template>
      </el-table-column>
      <el-table-column :label="$t('table.gender')"  width="100px" >
        <template slot-scope="scope">
        {{scope.row.gender | genderFilter }}
        </template>
      </el-table-column>
      <el-table-column :label="$t('table.contact_case')" min-width="200px" >
        <template slot-scope="scope">
        <span v-if="scope.row.newest_contact_content">{{scope.row.newest_contact_content}}</span>
        <span v-else></span>
        <span v-if="scope.row.newest_contact_content" class="link-type" @click='handleMoreContactRecord(scope.row)'>更多</span>
        <span v-else></span>
        <el-button icon="el-icon-tickets" @click='handleRecord(scope.row)' size="mini" >纪要</el-button>
        </template>
      </el-table-column>
      <el-table-column  align="center" :label="$t('table.actions')"  class-name="small-padding fixed-width" width="200px">
        <template slot-scope="scope">
          <el-button type="primary" size="mini"  @click="handleUpdate(scope.row)">{{$t('table.edit')}}</el-button>
          <el-button v-if="scope.row.status!='deleted'" size="mini" type="danger" @click="handleDelete(scope.row)">{{$t('table.delete')}}
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <el-dialog :title="textMap[contactPeopleDialogStatus]" :visible.sync="contactPeopleDescVisible" append-to-body>
      <el-form  :rules="rules" ref="dataForm" :model="temp" label-position="left" label-width="70px" style='width: 400px; margin-left:50px;'>
        <el-form-item :label="$t('table.degree')" prop="degree">
          <el-select class="filter-item" v-model="temp.degree" placeholder="Please select">
            <el-option v-for="item in degreeOptions " :key="item.key" :label="item.display_name" :value="item.key">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item :label="$t('table.name')" prop="name">
          <el-input v-model="temp.name"></el-input>
        </el-form-item>
        <el-form-item :label="$t('table.position')" prop="position">
          <el-input v-model="temp.position"></el-input>
        </el-form-item>
        <el-form-item :label="$t('table.mobile_phone')" prop="mobile_phone">
          <el-input v-model="temp.mobile_phone"></el-input>
        </el-form-item>
        <el-form-item :label="$t('table.gender')" prop="gender">
          <el-select class="filter-item" v-model="temp.gender" placeholder="Please select">
            <el-option v-for="item in genderOptions " :key="item.key" :label="item.display_name" :value="item.key">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item :label="$t('table.email')" prop="email">
          <el-input v-model="temp.email"></el-input>
        </el-form-item>
         <el-form-item :label="$t('table.telephone')" prop="telephone">
          <el-input v-model="temp.telephone"></el-input>
        </el-form-item>
        <el-form-item :label="$t('table.qq')" prop="qq">
          <el-input v-model="temp.qq"></el-input>
        </el-form-item>
        <el-form-item :label="$t('table.birthday_date')" prop="birthday_date">
          <el-date-picker v-model="temp.birthday_date" type="date" placeholder="选择日期" format="yyyy-MM-dd" value-format="timestamp" >
          </el-date-picker>
        </el-form-item>
        <el-form-item :label="$t('table.native_place')" prop="native_place">
          <el-input v-model="temp.native_place"></el-input>
        </el-form-item>
         <el-form-item :label="$t('table.account')" prop="account">
          <el-input v-model="temp.account"></el-input>
        </el-form-item>
         <el-form-item :label="$t('table.password')" prop="password">
          <el-input v-model="temp.password"></el-input>
        </el-form-item>
        <el-form-item :label="$t('table.comment')" prop="comment">
          <el-input v-model="temp.comment"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="contactPeopleDescVisible = false">{{$t('table.cancel')}}</el-button>
        <el-button v-if="contactPeopleDialogStatus=='create'" type="primary" @click="createData">{{$t('table.confirm')}}</el-button>
        <el-button v-else type="primary" @click="updateData">{{$t('table.confirm')}}</el-button>
      </div>
    </el-dialog>

    <el-dialog title="历史纪要" :visible.sync="dialogContactHistoryVisible" append-to-body>
      <el-table :data="this.contact_history_records" border fit highlight-current-row style="width: 100%" >
        <el-table-column label="时间" width="200px">
          <template slot-scope="contact_scope">
          {{ contact_scope.row.contact_time | timeFilter('{y}-{m}-{d} {h}:{i}:{s}') }}
          </template>
        </el-table-column>
        <el-table-column label="联系人" width="100px"> 
          <template slot-scope="contact_scope">
          {{ contact_scope.row.username }}
          </template>
        </el-table-column>
        <el-table-column label="纪要" width="300px"> 
          <template slot-scope="contact_scope">
          {{ contact_scope.row.contact_content }}
          </template>
        </el-table-column>
      </el-table>
      <div class="pagination-container">
      <el-pagination background 
        @size-change="handleContactHistorySizeChange" 
        @current-change="handleContactHistoryCurrentChange" 
        :current-page="contact_history_current_page" :page-sizes="[10,20,30, 50]"
        :page-size="contactHistoryListQuery.limit" layout="total, sizes, prev, pager, next" 
        :total="contactHistorytotal"
        >
      </el-pagination>
      </div>
    </el-dialog>

    <el-dialog title="新增纪要" :visible.sync="contactRecordVisible" append-to-body>
      <el-form  :rules="rules" ref="contactRecordForm" :model="contact_record" label-position="left" label-width="70px" style='width: 400px; margin-left:50px;'>
        <el-form-item :label="$t('table.contact_case')" prop="name">
          <el-input type="textarea" :rows="3" placeholder="请输入内容" v-model="contact_record.newest_contact"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="contactRecordVisible = false">{{$t('table.cancel')}}</el-button>
        <el-button type="primary" @click="addRecord">{{$t('table.confirm')}}</el-button>
      </div>
    </el-dialog>

  </div>
</template>

<script>
import API from '@/utils/backend_api'
import Static_Data from '@/data/index'
import waves from '@/directive/waves' // 水波纹指令

const degreeOptions = Static_Data.contact_people_degree
const genderOptions = Static_Data.gender

export default {
  name: 'companyContactPeople',
  props: {
    id: {
      type: String,
      default: '' // 这样可以指定默认的值
    }
  },
  directives: {
    waves
  },
  data() {
    return {
      contactHistorytotal: 0,
      contact_history_current_page: 1,
      contactHistoryListQuery: {
        page: 1,
        offset: 0,
        limit: 10,
        contact_people_id: '',
        company_id: ''
      },
      contactRecordVisible: false,
      dialogContactHistoryVisible: false,
      degreeOptions: degreeOptions,
      genderOptions: genderOptions,
      contactPeopleDescVisible: false,
      contactPeopleDialogStatus: '',
      textMap: {
        update: '编辑客户联系人',
        create: '新增客户联系人'
      },
      tableKey: 0,
      list: null,
      total: null,
      listLoading: false,
      rules: {
        // degree: [{ required: true, message: 'degree is required', trigger: 'change' }]
        // // timestamp: [{ type: 'date', required: true, message: 'timestamp is required', trigger: 'change' }],
        // title: [{ required: true, message: 'title is required', trigger: 'blur' }]
      },
      contact_history_records: [],
      contact_record: {
        newest_contact: ''
      },
      temp: {
        id: '',
        name: '',
        position: '',
        mobile_phone: '',
        email: '',
        telephone: '',
        qq: '',
        gender: '',
        birthday_date: '',
        native_place: '',
        account: '',
        password: '',
        comment: '',
        degree: '',
        company_id: '',
        newest_contact_content: '',
        newest_contact_time: ''
      }
    }
  },
  filters: {
  },
  created() {
    this.getList()
  },
  watch: {
    id: function(val, oldVal) {
      console.log('当前值为：' + val, '旧值为：' + oldVal)
      this.getList()
    }
  },
  methods: {
    resetContactRecord() {
      this.contact_record = {
        newest_contact: ''
      }
    },
    resetTemp() {
      this.temp = {
        id: '',
        name: '',
        position: '',
        mobile_phone: '',
        email: '',
        telephone: '',
        qq: '',
        gender: '',
        birthday_date: '',
        native_place: '',
        account: '',
        password: '',
        comment: '',
        degree: '',
        company_id: '',
        newest_contact_content: '',
        newest_contact_time: ''
      }
    },
    getList() {
      if (this.id && this.id !== '') {
        this.listLoading = true
        API.contact_people.all(this.id, { sort: '-newest_contact_time' }).then(response => {
          this.list = response.data
          if (response.headers && response.headers['x-total-count']) {
            this.total = Number(response.headers['x-total-count'])
          }
          this.listLoading = false
        })
      }
    },
    handleCreate() {
      this.resetTemp()
      this.contactPeopleDialogStatus = 'create'
      this.contactPeopleDescVisible = true
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
    },
    handleUpdate(row) {
      this.temp = Object.assign({}, row) // copy obj
      this.contactPeopleDialogStatus = 'update'
      this.contactPeopleDescVisible = true
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
    },
    handleMoreContactRecord(data) {
      if (data && data.id) {
        this.contactHistoryListQuery.contact_people_id = data.id
        this.contactHistoryListQuery.company_id = data.company_id
        this.getContactHistoryList(this.contactHistoryListQuery)
        this.dialogContactHistoryVisible = true
      }
    },
    getContactHistoryList(query) {
      if (query && query.contact_people_id && query.company_id) {
        API.contact_people.contact_records(query).then(response => {
          this.contact_history_records = response.data
          if (response.headers && response.headers['x-total-count']) {
            this.contactHistorytotal = Number(response.headers['x-total-count'])
          }
        })
      } else {
        this.$message({
          showClose: true,
          message: '请先选择联系人',
          type: 'warning'
        })
      }
    },
    handleContactHistorySizeChange(val) {
      this.contactHistoryListQuery.limit = val
      this.getContactHistoryList(this.contactHistoryListQuery)
    },
    handleContactHistoryCurrentChange(val) {
      if (val >= 1) {
        this.contact_history_current_page = val
        this.contactHistoryListQuery.offset = (val - 1) * this.contactHistoryListQuery.limit
        this.getContactHistoryList(this.contactHistoryListQuery)
      }
    },
    handleRecord(row) {
      this.resetContactRecord()
      this.contact_record.company_id = this.id
      this.contact_record.people_id = row.id
      this.contactRecordVisible = true
      this.$nextTick(() => {
        this.$refs['contactRecordForm'].clearValidate()
      })
    },
    addRecord() {
      this.$refs['contactRecordForm'].validate((valid) => {
        if (valid) {
          API.contact_people.addContact(this.id, this.contact_record.people_id, this.contact_record.newest_contact).then((response) => {
            for (const v of this.list) {
              if (v.id === this.contact_record.people_id) {
                const index = this.list.indexOf(v)
                this.list.splice(index, 1, response.data)
                break
              }
            }
            this.contactRecordVisible = false
            this.$notify({
              title: '成功',
              message: '保存成功',
              type: 'success',
              duration: 2000
            })
          })
        }
      })
    },
    createData() {
      this.$refs['dataForm'].validate((valid) => {
        if (valid) {
          API.contact_people.add(this.id, this.temp).then((response) => {
            console.log(response)
            this.list.unshift(response.data)
            this.contactPeopleDescVisible = false
            this.$notify({
              title: '成功',
              message: '创建成功',
              type: 'success',
              duration: 2000
            })
          })
        }
      })
    },
    handleDelete(row) {
      this.$confirm('此操作将永久删除该数据, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        API.contact_people.del(this.id, row.id).then(response => {
          this.$notify({
            title: '成功',
            message: '删除成功',
            type: 'success',
            duration: 2000
          })
          const index = this.list.indexOf(row)
          this.list.splice(index, 1)
        })
      }).catch(() => {
        this.$notify({
          type: 'info',
          message: '已取消删除'
        })
      })
    },
    updateData() {
      this.$refs['dataForm'].validate((valid) => {
        if (valid) {
          const tempData = Object.assign({}, this.temp)
          API.contact_people.update(this.id, tempData).then((response) => {
            for (const v of this.list) {
              if (v.id === this.temp.id) {
                const index = this.list.indexOf(v)
                this.list.splice(index, 1, response.data)
                break
              }
            }
            this.contactPeopleDescVisible = false
            this.$notify({
              title: '成功',
              message: '更新成功',
              type: 'success',
              duration: 2000
            })
          })
        }
      })
    }
  }
}
</script>

<style>
  .demo-table-expand {
    font-size: 0;
  }
  .demo-table-expand label {
    width: 90px;
    color: #99a9bf;
  }
  .demo-table-expand .el-form-item {
    margin-right: 0;
    margin-bottom: 0;
    width: 50%;
  }
</style>